﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ilanver.Core.CommonValidator;

namespace ilanver.Web.CommonValidator
{
    [Obsolete("This binder is very limited in nature.  While it remains for backward compatibility, it " +
       "is highly recommended to instead use SharpArch.Web.ModelBinder.SharpModelBinder which is much " +
       "more seamlessly integrated with the SharpArch libraries and repository support.")]
    public class ValidatableModelBinder : DefaultModelBinder
    {
        protected override void OnModelUpdated(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {

            IValidatable model = bindingContext.Model as IValidatable;

            if (model != null)
            {
                if (!model.IsValid())
                {
                    foreach (IValidationResult validationResult in model.ValidationResults())
                    {
                        bindingContext.ModelState
                            .AddModelError(validationResult.ClassContext.Name +
                            (!string.IsNullOrEmpty(validationResult.PropertyName)
                                ? "." + validationResult.PropertyName
                                : ""),
                        validationResult.Message);
                    }
                }
            }
        }

        protected override void OnPropertyValidated(ControllerContext controllerContext,
            ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
        {
            // Do nothing
        }
    }
}
